package com.example.demo.jvm;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Scanner;

// 直接内存举例
public class Buffer {
    public static final int BUFFER = 1024 * 1024 * 1024;

    public static void main(String[] args) {
        // 申请1GB的直接内存，通过任务管理器可以查看
        System.out.println("申请直接内存1GB");
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(BUFFER);

        Scanner sc = new Scanner(System.in);
        sc.next();

        // 释放内存
        byteBuffer = null;
        System.out.println("释放内存");
    }

    // 使用直接内存读写
    public static final int _100Mb = 1024 * 1024 * 100;
    private static void directBuffer(String src, String dest) {
        try (FileChannel in = new FileInputStream(src).getChannel();
        FileChannel out = new FileInputStream(dest).getChannel()) {
            ByteBuffer byteBuffer = ByteBuffer.allocateDirect(_100Mb);
            while (in.read(byteBuffer) != -1) {
                byteBuffer.flip();// 修改为读数据模式
                out.write(byteBuffer);
                byteBuffer.clear();// 清空
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
